<template>
  <div class="main">
    <!-- fluid 属性使容器全宽。 -->
    <v-container fluid>
      <v-row>
        <v-col cols="12" class="text-center">
                <!-- <v-expansion-panels>: 用于显示可展开的面板，可以包含多个面板。 -->
          <v-expansion-panels>
            <v-expansion-panel>
              <v-expansion-panel-header>
                <v-row align="center">
                  <v-col cols="12">
                    <span>以太网设置</span>
                  </v-col>
                </v-row>
          
              </v-expansion-panel-header>
              <v-expansion-panel-content>
                <v-container fluid>
                  <v-row align="center">
                    <v-col cols="4" class="d-flex justify-center text-center">
                      <div class="config-item">
                        IP地址
                      </div>
                    </v-col>
                    <v-col cols="8" class="d-flex text-center">
                      <v-text-field
                          v-model="ethernetIpAddress"
                          label="192.168.3.3"
                          class="config-content justify-center"
                          dense
                          :disabled=autoGetEthernetIP
                          hide-details></v-text-field>
                    </v-col>
                  </v-row>
                  <v-row align="center">
                    <v-col cols="4" class="d-flex justify-center text-center">
                      <div class="config-item">
                        子网掩码
                      </div>
                    </v-col>
                    <v-col cols="8" class="d-flex text-center">
                      <!-- <v-text-field>: 用于输入以太网的 IP 地址。
                       v-model 绑定组件的数据。
                       label 提供默认值。
                       class 设置样式类。
                       dense 属性使输入框更紧凑。
                       :disabled 属性根据 autoGetEthernetIP 的值决定是否禁用输入框。
                       hide-details 隐藏输入框的提示信息。 -->
                      <v-text-field
                          v-model="ethernetMask"
                          label="255.255.0.0"
                          class="config-content"
                          dense
                          :disabled=autoGetEthernetIP
                          hide-details></v-text-field>
                    </v-col>
                  </v-row>
                  <!-- 添加一个复选框，用于选择是否自动获取以太网的 IP 地址。 -->
                  <v-row align="center" justify="center">
                    <v-checkbox
                        v-model="autoGetEthernetIP"
                        dense
                        label="自动获取IP地址"></v-checkbox>
                  </v-row>
                </v-container>
              </v-expansion-panel-content>
            </v-expansion-panel>
              <!-- 创建另一个可折叠面板，标题为“WIFI设置”，点击时调用 getWifi 方法。 -->
            <v-expansion-panel>
              <v-expansion-panel-header @click="getWifi">
                <v-row align="center">
                  <v-col cols="12">
                    <span>WIFI设置</span>
                  </v-col>
                </v-row>
              </v-expansion-panel-header>

              <!-- 创建一行用于选择 Wi-Fi 名称的下拉菜单。 -->
              <v-expansion-panel-content>
                <v-container fluid>
                  <v-row align="center">
                    <v-col cols="4" class="d-flex justify-center text-center">
                      <div class="config-item">
                        WIFI名
                      </div>
                    </v-col>
                    <v-col cols="8" class="d-flex text-center">
                      <v-select
                          v-model="wifiName"
                          label="请选择WIFI"
                          class="config-content"
                          :items="wifiList"
                          item-text="txt"
                          item-value="txt"
                          dense
                          @change="checkWifi()"
                          :error-messages="wifiNameError ? [wifiNameError] : []"
                          hide-details
                          no-data-text="未检测到可用WIFI"
                          :menu-props="{
                            offsetY: true,
                            nudgeTop: 10,
                            maxHeight: '300'
                          }"
                      ></v-select>
                    </v-col>
                  </v-row>
                  <!-- 创建一行用于输入 Wi-Fi 密码的文本框，支持密码可见性切换。 -->
                  <v-row align="center">
                    <v-col cols="4" class="d-flex justify-center text-center">
                      <div class="config-item">
                        WIFI密码
                      </div>
                    </v-col>
                    <v-col cols="8" class="d-flex text-center">
                      <v-text-field
                          :type="showPassword ? 'text' : 'password'"
                          v-model="wifiPwd"
                          label="请输入您的WIFI密码"
                          class="config-content"
                          dense
                          hide-details
                          @change="checkWifi()"
                          :error-messages="wifiPasswordError ? [wifiPasswordError] : []"
                          :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
                          @click:append="togglePasswordVisibility"></v-text-field>
                    </v-col>
                  </v-row>
                </v-container>
              </v-expansion-panel-content>
            </v-expansion-panel>
          </v-expansion-panels>
        </v-col>
      </v-row>
      <v-row align="center" justify="center" class="button-container">
        <v-col cols="12" class="text-center">
          <v-btn @click="openMore" class="mx-2"
                 style="background-color: transparent; border: none; box-shadow: none; padding: 0">
            <v-icon left>mdi-cog</v-icon>
            高级设置
          </v-btn>
          <!--          <v-btn color="primary" @click="openMore" class="mx-2" style="width: 200px;">-->
          <!--            <v-icon left>mdi-cog</v-icon>-->
          <!--            高级设置-->
          <!--          </v-btn>-->
        </v-col>
      </v-row>
      <v-row align="center" justify="center" class="button-container">
        <v-col cols="2" class="text-center">
          <v-btn @click="refresh" class="refresh-btn" style="background-color: #003366; color: white; width: 100%;">
            刷新
          </v-btn>
        </v-col>
        <v-col cols="2" class="text-center">
          <v-btn class="save-btn" @click="save" style="background-color: #FFA500; color: white; width: 100%;">
            保存
          </v-btn>
        </v-col>
      </v-row>
    </v-container>
    <v-dialog
        v-model="dialog"
        persistent
        content-class="text-center"
        max-width="800"
        class="settings-dialog">
      <v-card>
        <v-card-title class="headline text-h5 settings-title">
          <div class="title-content">高级网络设置</div>
        </v-card-title>
        <v-card-actions class="settings-content">
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-expansion-panels>
                  <v-expansion-panel>
                    <v-expansion-panel-header>
                      <span>以太网高级设置</span>
                    </v-expansion-panel-header>
                    <v-expansion-panel-content>
                      <v-row align="center">
                        <v-col cols="4" class="d-flex justify-center text-center">
                          <div class="config-item">
                            默认网关
                          </div>
                        </v-col>
                        <v-col cols="8" class="d-flex text-center">
                          <v-text-field
                              v-model="temp.ethernetDefaultGateway"
                              label="192.168.3.1"
                              class="config-content"
                              dense
                              hide-details></v-text-field>
                        </v-col>
                      </v-row>
                    </v-expansion-panel-content>
                  </v-expansion-panel>
                  <v-expansion-panel>
                    <v-expansion-panel-header>
                      <span>WIFI高级设置</span>
                    </v-expansion-panel-header>
                    <v-expansion-panel-content>
                      <v-row align="center">
                        <v-col cols="4" class="d-flex justify-center text-center">
                          <div class="config-item">
                            IP地址
                          </div>
                        </v-col>
                        <v-col cols="8" class="d-flex text-center">
                          <v-text-field
                              v-model="temp.wifiIpAddress"
                              label="192.168.100.20"
                              class="config-content justify-center"
                              dense
                              :disabled=temp.autoGetWifiIp
                              hide-details></v-text-field>
                        </v-col>
                      </v-row>
                      <v-row align="center">
                        <v-col cols="4" class="d-flex justify-center text-center">
                          <div class="config-item">
                            默认网关
                          </div>
                        </v-col>
                        <v-col cols="8" class="d-flex text-center">
                          <v-text-field
                              v-model="temp.wifiDefaultGateway"
                              label="192.168.100.1"
                              class="config-content"
                              dense
                              :disabled=temp.autoGetWifiIp
                              hide-details></v-text-field>
                        </v-col>
                      </v-row>
                      <v-row align="center">
                        <v-col cols="4" class="d-flex justify-center text-center">
                          <div class="config-item">
                            子网掩码
                          </div>
                        </v-col>
                        <v-col cols="8" class="d-flex text-center">
                          <v-text-field
                              v-model="temp.wifiMask"
                              label="255.255.0.0"
                              class="config-content"
                              dense
                              :disabled=temp.autoGetWifiIp
                              hide-details></v-text-field>
                        </v-col>
                      </v-row>
                      <v-row align="center" justify="center">
                        <v-checkbox
                            v-model="temp.autoGetWifiIp"
                            dense
                            label="自动获取IP地址"></v-checkbox>
                      </v-row>
                    </v-expansion-panel-content>
                  </v-expansion-panel>
                </v-expansion-panels>
              </v-col>
            </v-row>
            <v-row>
              <v-col cols="6">
                <v-btn @click="dialog = false">取消</v-btn>
              </v-col>
              <v-col cols="6">
                <v-btn @click="sure">确定</v-btn>
              </v-col>
            </v-row>
          </v-container>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
// 定义了三个正则表达式，用于验证 IP 地址、子网掩码和默认网关的格式。
const ipRule = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/
const maskRule = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)$/
const gatewayBaseRule = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
export default {
  name: 'NetworkSettingsComponent',
  created() {

  },

  // 
  data() {
    return {
      panelOpen: false,
      nic: 'ETH0',
      ethernetIpAddress: '',
      wifiIpAddress: '',
      ethernetDefaultGateway: '',
      wifiDefaultGateway: '',
      ethernetMask: '',
      wifiMask: '',
      wifiName: '',
      wifiNameError: '',
      showPassword: false,
      wifiPwd: '',
      wifiPasswordError: '',
      autoGetEthernetIP: true,
      autoGetWifiIp: true,
      dialog: false,
      temp: {
        ethernetDefaultGateway: '',
        wifiIpAddress: '',
        wifiDefaultGateway: '',
        wifiMask: '',
        autoGetWifiIp: true,
      },
      wifiList: []
    };
  },
  methods: {
    async getWifi() {
      try {
        const networks = await window.electronAPI.getWifiNetworks();
        networks.forEach((wifi) => {
          this.wifiList.push({txt: wifi.ssid})
        })
        // console.log(networks);
      } catch (err) {
        console.log(err)
      }
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    checkWifi() {
      this.wifiNameError = '';
      this.wifiPasswordError = '';
      if (this.wifiName === '') {
        this.wifiNameError = 'Wifi名不能为空！'
        return true;
      }
      if (this.wifiPwd === '') {
        this.wifiPasswordError = 'Wifi密码不能为空！'
        return true;
      }
      return false;
    },
    refresh() {
      // 刷新逻辑
      localStorage.setItem('curItem', '网络设置');
      this.$emit('refresh')
    },
    save() {
      if (this.checkEthernetData()) {
        const formattedConfig = {
          "cmd": 241,
          "config": {
            "ethernet": {
              'ETH0': {
                "bootproto": this.autoGetEthernetIP ? 1 : 0,
                "type": 0,
                "ipaddr": this.ethernetIpAddress,
                "mask": this.ethernetMask,
                "gateway": this.ethernetDefaultGateway
              }
            }
          }
        };
        const jsonData = JSON.stringify(formattedConfig);
        this.$emit('sendData', jsonData);
      }
      if (this.checkWifi()) return;
      if (this.checkWifiData()) {
        const formattedData = {
          "cmd": 242,
          "config": {
            "wlan": {
              'WLAN0': {
                'bootproto': this.autoGetWifiIp ? 1 : 0,
                'type': 1,
                'ipaddr': this.wifiIpAddress,
                'mask': this.wifiMask,
                'gateway': this.wifiDefaultGateway,
                'wlan-name': this.wifiName,
                'wlan-password': this.wifiPwd
              }
            }
          }
        }
        const jsonData = JSON.stringify(formattedData);
        this.$emit('sendData', jsonData);
      }
    },
    openMore() {
      this.dialog = true;
      this.temp.autoGetWifiIp = this.autoGetWifiIp;
      this.temp.ethernetDefaultGateway = this.ethernetDefaultGateway;
      this.temp.wifiDefaultGateway = this.wifiDefaultGateway;
      this.temp.wifiMask = this.wifiMask;
      this.temp.wifiIpAddress = this.wifiIpAddress;
    },
    sure() {
      this.autoGetWifiIp = this.temp.autoGetWifiIp;
      this.ethernetDefaultGateway = this.temp.ethernetDefaultGateway;
      this.wifiDefaultGateway = this.temp.wifiDefaultGateway;
      this.wifiMask = this.temp.wifiMask;
      this.wifiIpAddress = this.temp.wifiIpAddress;
      this.dialog = false;
    },
    checkEthernetData() {
      if (!this.autoGetEthernetIP) {
        if (!ipRule.test(this.ethernetIpAddress)) {
          this.$emit('errMsg', 'IP格式有误');
          return false;
        } else if (!gatewayBaseRule.test(this.ethernetDefaultGateway)) {
          this.$emit('errMsg', '网关格式有误');
          return false;
        } else if (!maskRule.test(this.ethernetMask)) {
          this.$emit('errMsg', '子网掩码格式有误');
          return false;
        } else {
          let judgeIp = [];
          let judgeMask = [];
          let judgeGateway = [];
          judgeIp = this.ethernetIpAddress.split('.');
          judgeMask = this.mask.split('.');
          judgeGateway = this.ethernetDefaultGateway.split('.')
          const res0 = parseInt(judgeIp[0]) & parseInt(judgeMask[0]);
          const res1 = parseInt(judgeIp[1]) & parseInt(judgeMask[1]);
          const res2 = parseInt(judgeIp[2]) & parseInt(judgeMask[2]);
          const res3 = parseInt(judgeIp[3]) & parseInt(judgeMask[3]);

          const res0_gw = parseInt(judgeGateway[0]) & parseInt(judgeMask[0]);
          const res1_gw = parseInt(judgeGateway[1]) & parseInt(judgeMask[1]);
          const res2_gw = parseInt(judgeGateway[2]) & parseInt(judgeMask[2]);
          const res3_gw = parseInt(judgeGateway[3]) & parseInt(judgeMask[3]);

          if (!(res0 === res0_gw && res1 === res1_gw && res2 === res2_gw && res3 === res3_gw)) {
            this.$emit('errMsg', '网关配置有误');
            return false;
          }
        }
      }
      return true;
    },
    checkWifiData() {
      if (!this.autoGetWifiIp) {
        if (!ipRule.test(this.wifiIpAddress)) {
          this.$emit('errMsg', 'IP格式有误');
          return false;
        } else if (!gatewayBaseRule.test(this.wifiDefaultGateway)) {
          this.$emit('errMsg', '网关格式有误');
          return false;
        } else if (!maskRule.test(this.mask)) {
          this.$emit('errMsg', '子网掩码格式有误');
          return false;
        } else {
          let judgeIp = [];
          let judgeMask = [];
          let judgeGateway = [];
          judgeIp = this.wifiIpAddress.split('.');
          judgeMask = this.mask.split('.');
          judgeGateway = this.wifiDefaultGateway.split('.')
          const res0 = parseInt(judgeIp[0]) & parseInt(judgeMask[0]);
          const res1 = parseInt(judgeIp[1]) & parseInt(judgeMask[1]);
          const res2 = parseInt(judgeIp[2]) & parseInt(judgeMask[2]);
          const res3 = parseInt(judgeIp[3]) & parseInt(judgeMask[3]);

          const res0_gw = parseInt(judgeGateway[0]) & parseInt(judgeMask[0]);
          const res1_gw = parseInt(judgeGateway[1]) & parseInt(judgeMask[1]);
          const res2_gw = parseInt(judgeGateway[2]) & parseInt(judgeMask[2]);
          const res3_gw = parseInt(judgeGateway[3]) & parseInt(judgeMask[3]);

          if (!(res0 === res0_gw && res1 === res1_gw && res2 === res2_gw && res3 === res3_gw)) {
            this.$emit('errMsg', '网关配置有误');
            return false;
          }
        }
      }
      return true;
    }
  }
};
</script>

<style>
/* 可添加自定义样式 */
.main {
  width: 100%;
  padding: 10vh 10vw 0 10vw;
}

.refresh-btn {
  background-color: #003366;
  color: white;
  margin-right: 10px;
}

.title-content {
  width: 100%;
  text-align: center;
}

.settings-dialog {
  min-width: 700px;
  max-width: 800px;
}

.settings-title {
  border-bottom: 1px solid #ccc;
}

.settings-content {
  justify-content: space-between;
  padding: 0 5vw 0 5vw !important;
}
</style>
